import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from '../utils/token-utils'
import type { UserInfoState } from './interface'
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoutes } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router'
import { cloneDeep } from 'lodash'
import router from '../router'

import { loginApi, logoutApi, userInfoApi } from '@/api/login/loginApi'

// 定义过滤动态路由的方法
function getDynamicRouting(
  allAsyncRoutes: Array<RouteRecordRaw>,
  routes: string[]
) {
  return allAsyncRoutes.filter((route) => {
    if (routes.includes(route.name as string)) {
      if (route.children?.length) {
        route.children = getDynamicRouting(route.children, routes)
      }
      return true
    }
    return false
  })
}

// 添加动态路由的方法
function addRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((route) => {
    router.addRoute(route)
  })
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttons: [],
    routes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      const res = await loginApi(username, password)
      setToken(res.token)
      this.token = res.token
    },

    async getInfo() {
      const res = await userInfoApi()
      this.name = res.name
      this.avatar = res.avatar
      this.routes = res.routes
      console.log(res.routes)
      this.buttons = res.buttons
      const dynamicRoute = getDynamicRouting(
        cloneDeep(allAsyncRoutes),
        this.routes
      )
      this.menuRoutes = [...staticRoutes, ...dynamicRoute]
      addRoutes([...dynamicRoute, ...anyRoutes])
    },

    async reset() {
      await logoutApi() // 删除服务器中的token
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
  },
})
